<template>
	<!-- 搜索框 -->
	<view class="search-bar">
		<u-search v-model="searchQuery" placeholder="搜索农作物仓库..." />
	</view>

	<!-- 仓库列表 -->
	<view class="warehouse">
		<view v-for="(item, index) in filteredWarehouseItems" :key="index" class="warehouse-item"
			@click="jeep(item)">
			<!-- 左侧农作物图片 -->
			<view class="crop-image">
				<image :src="`/img` + item.remark" mode="aspectFill" class="image" />
			</view>
			<!-- 右侧商品详细信息 -->
			<view class="item-info">
				<!-- 				<text class="item-name">{{ item.warehouseName }}</text> -->
				<text class="item-name">{{ item.warehouseDescription }}</text>
				<br />
				<text class="item-details">设备:6台 工人:2人</text>

				<view class="item-location">
					<text class="location-icon">📍</text>
					<text>{{ item.tregion.city }}</text>
				</view>
			</view>
		</view>
	</view>

	<!-- 下拉加载提示 -->
	<view v-if="isLoading" class="loading">加载中...</view>
	<view v-if="noMore" class="no-more">没有更多数据了</view>
</template>

<script>
import {
    ref,
    computed,
    onMounted,
    onUnmounted
} from 'vue';
import {
    warehousedata
} from '@/common/api.js';
import {
    useUserStore
} from '@/stores/user.js';

export default {
    setup() {
        const userStore = useUserStore(); // 获取用户数据
        const searchQuery = ref(''); // 搜索框输入

        // 定义分页响应式变量
        const page = ref({
            size: 9,
            currentPage: 1
        });

        // 是否正在加载数据
        const isLoading = ref(false);
        // 是否已经加载完所有数据
        const noMore = ref(false); // 确保 noMore 已经定义
        // 假设的日志记录数据
        const logs = ref([]);

        // 计算属性来过滤日志记录
        const filteredWarehouseItems = computed(() => {
            if (searchQuery.value) {
                return logs.value.filter(
                    (log) =>
                        log.operation.includes(searchQuery.value) ||
                        String(log.logId).includes(searchQuery.value) // 确保 log_id 是字符串
                );
            } else {
                return logs.value;
            }
        });
	// 获取商品详情
	const jeep = (item) => {
		console.log(item.warehouseDescription);
		wx.redirectTo({
			url: `/pages/warehouse/Detail?id=${item.warehouseDescription}&regionId=${item.regionId}`
		});
	};


        // 数据请求函数
        const logselect = async (params) => {
            if (isLoading.value || noMore.value) return; // 防止重复请求或没有更多数据

            isLoading.value = true;
            try {
                const res = await warehousedata(params);

                if (res.code === 200) {
                    // 将新的数据追加到现有数据中
                    logs.value = [...logs.value, ...res.data];
                    // 判断返回的数据长度，如果小于当前页大小，则不再继续查询
                    if (res.data.length < page.value.size) {
                        console.log('没有更多数据了');
                        noMore.value = true; // 停止继续加载更多数据
                    }
                }
            } catch (error) {
                console.error('请求失败:', error);
            } finally {
                isLoading.value = false;
            }
        };

        // 页面挂载时的初始化
        onMounted(() => {
            console.log(userStore.userId);

            // 初始加载数据
            const params = {
                size: page.value.size,
                currentPage: page.value.currentPage,
                userId: userStore.userId,
            };
            logselect(params);
        });

        // 页面卸载时清理逻辑
        onUnmounted(() => {
            // 可以在这里执行一些页面卸载时需要清理的操作
        });

        // 下拉刷新处理函数
        const onPullDownRefresh = () => {
            // 重置数据
            page.value.currentPage = 1;
            logs.value = [];
            noMore.value = false;

            const params = {
                size: page.value.size,
                currentPage: page.value.currentPage,
                userId: userStore.userId,
            };
            logselect(params).then(() => {
                // 停止下拉刷新动画
                uni.stopPullDownRefresh();
            });
        };

        // 微信小程序中的上拉加载更多处理函数
        const onReachBottom = () => {
            console.log("触底事件触发");
            if (!noMore.value) {
                page.value.currentPage += 1; // 增加页码
                const params = {
                    size: page.value.size,
                    currentPage: page.value.currentPage,
                    userId: userStore.userId
                };
                logselect(params); // 加载更多数据
            }
        };

        return {
			jeep,
            page,
            logs,
            isLoading,
            noMore,
            searchQuery,
            filteredWarehouseItems,
            logselect,
            onPullDownRefresh,
            onReachBottom
        };
    },
    // 注册小程序的生命周期函数
    onReachBottom() {
        this.onReachBottom();
    },
    onPullDownRefresh() {
        this.onPullDownRefresh();
    }
};
</script>


<style scoped>
	.loading,
	.no-more {
		text-align: center;
		padding: 16px;
	}

	.container {
		padding: 20px;
		/* background-color: #f5f5f5; */
	}

	.search-bar {
		margin-bottom: 20px;
		display: flex;
		justify-content: center;
		margin-top: 10px;
	}

	.warehouse {
		display: flex;
		flex-direction: column;
	}

	.warehouse-item {
		display: flex;
		align-items: center;
		margin-bottom: 15px;
		background-color: #fff;
		padding: 15px;
		border-radius: 8px;
		box-shadow: 0 0 8px rgba(0, 0, 0, 0.1);
	}

	.crop-image {
		flex: 1;
	}

	.image {
		width: 100px;
		height: 100px;
		border-radius: 8px;
		object-fit: cover;
		border: 1px solid #ccc;
	}

	.item-info {
		flex: 3;
		padding-left: 15px;
	}

	.item-name {
		font-size: 18px;
		font-weight: bold;
		margin-bottom: 8px;
	}

	.item-description {
		font-size: 14px;
		margin-bottom: 8px;
		color: #666;
	}

	.item-details {
		font-size: 14px;
		margin-bottom: 8px;
		color: #888;
	}

	.item-location {
		display: flex;
		align-items: center;
		font-size: 14px;
		color: #333;
	}

	.location-icon {
		margin-left: 5px;
	}
</style>